package cn.itsource.controller;

import cn.itsource.domain.User;
import cn.itsource.query.UserQuery;
import cn.itsource.service.UserService;
import cn.itsource.util.AjaxResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 接口类：用户User
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public List<User> findAll(){
        return userService.findAll();
    }

    /**
     * 查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id")Long id){
        return userService.findOne(id);
    }

    /**
     * 添加和修改
     * @param user
     * @return
     */
    @PutMapping
    public AjaxResult addorUpdate(@RequestBody User user){
        try {
            if(user.getId()==null){//添加操作
                userService.add(user);
            }else{
                userService.update(user);
            }
            //如果成功
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{ld}")
    public AjaxResult delete(@PathVariable("ld")Long id){
        try {
            userService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

    /**
     * 分页查询 + 高级查询
     * @param query
     * @return
     */
    @PostMapping
    public PageInfo<User> pageQuery(@RequestBody UserQuery query){
        return userService.pageQuery(query);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids){  //["2","14"] - Long[] ids
        try {
            userService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

}
